<?php


namespace app\api\controller;


use app\BaseController;

use app\common\Sms;
use app\common\Tencent;
use app\event\UserLogin;
use app\model\A;
use app\model\Article;
use app\model\ArticleType;
use app\model\Company;
use app\model\LeasingCompany as SelfModel;
use app\model\MemberMessage;
use app\model\MemberToken;
use app\model\Worker;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\Label\Font\NotoSans;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;
use think\App;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Queue;
use think\Request;
use think\queue\Job;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendBatchSmsRequest;
use think\facade\Event;
use thans\jwt\facade\JWTAuth;
use think\Response;
use think\facade\Db;
class Index extends Base
{
    private $start_time;
    protected $end_time;
    public function __construct(App $app)
    {
       $this->start_time= mktime(10,30,0);
       $this->end_time = mktime(22,30,0);
       $this->secend = $this->end_time-$this->start_time;
    }

    public function clear()
    {
        $company = Company::select();
        foreach ($company as $v){
            $v->save(['end_number'=>0]);
        }
        $depart = \app\model\Depart::select();
        foreach ($depart as $v){
            $v->save(['end_number'=>0]);
        }
        $workertype = \app\model\WorkerType::select();
        foreach ($workertype as $v){
            $v->save(['end_number'=>0]);
        }
        $worker = \app\model\Worker::select();
        foreach ($worker as $v){
            $v->save(['end_number'=>0]);
        }
    }

    public function zero($data){
        if($data<10){
            $data = '0'.$data;
        }
        return $data;
    }

    public function countdown($start_time='',$end_time=''){
        // 设置目标日期/时间（这里为2021年1月1日）
//        $start_time = $this->start_time;
//        $end_time = $this->end_time;
        $sta = time()-$this->start_time;//计算秒数

        if($sta<0){ //未开始
            return '00:00:00';
        }elseif (time()-$this->end_time>0){ //结束
            return '00:00:00';
        }else{
            $targetDate = strtotime($this->end_time); // 将日期转换成UNIX时间戳格式
            // 获取当前日期/时间
            $currentTime = time(); // 获取当前UNIX时间戳
            // 计算距离目标日期还有多少天、小时、分钟和秒
            $timeDiff = $this->end_time-$currentTime;
            $daysRemaining = floor($timeDiff / (60 * 60 * 24));
            $hoursRemaining = floor(($timeDiff % (60 * 60 * 24)) / (60 * 60));
            $minutesRemaining = floor((($timeDiff % (60 * 60 * 24)) % (60 * 60)) / 60);
            $secondsRemaining = ($timeDiff % (60 * 60 * 24)) % (60 * 60) % 60;
            return $countdown = "{$this->zero($hoursRemaining)}:{$this->zero($minutesRemaining)}:{$this->zero($secondsRemaining)}";
        }

    }

    public function countdownif($v){
        if(time() >= $this->start_time && time() <= $this->end_time){

            $v['end_number'] = price($v['end_number']-(time()-$this->start_time)*$v['start_number']/($this->end_time-$this->start_time));
        }
        if(time() < $this->start_time ){ //未开始

            $v['end_number'] = 0;
        }
        if(time() > $this->end_time ){ //已过时

          //  $v['end_number'] = price($v['end_number']-($this->end_time-$this->start_time)*$v['start_number']/($this->end_time-$this->start_time));
            $v['end_number'] = 0;
        }

    }

    public function paiming(Request $request)
    {
        $type = [1=>'公司',2=>'部门',3=>'员工'];
        $data['top'] = date('Y-m-d');
        $data['name'] = Company::where('id',$request->id)->value('title') ?? 0;
        $data['yesterday'] = round(\app\model\WorkerRecords::where('company_id',$request->id)->whereTime('create_time','yesterday')->sum('price'));
        $data['today'] = round(Company::where('id',$request->id)->value('end_number'));
        $data['countdown'] =$this->countdown();
//        $left = Worker::field('id,name,end_number,start_number')->where('end_number',0)->select();
//        $i=0;
//        foreach ($left as &$v){
//            //$v['end_number'] = round(-$v['start_number']+$v['end_number']+(time()-$this->start_time)*$v['start_number']/($this->end_time-$this->start_time));
//        $this->countdownif($v);
//        }
//        $left = list_order($left->toArray(),'end_number','desc');
//        $j=0;
//        foreach ($left as &$vv){
//            $vv['no'] = ++$j;
//        }
//        $data['left'] = $left;where('end_number','>',0)->
        $al = Worker::field('id,name,end_number,start_number')->order('end_number','desc')->select();
        $data['left'] = [];
        foreach ($al as &$v){
            $this->countdownif($v);
        }
        $all = list_order($al->toArray(),'end_number','desc');
        $middle = [];
        $right = [];
        $i=0;

        $right_count = ceil((count($all)-3)/2);
        foreach ($all as $k=> &$v){
            $v['no'] = ++$i;
            if($k<3){
                $middle[] = $v;
            }elseif($k>=3 && $k<=$right_count){
                $right[] = $v;
            }elseif ($k>$right_count){

                $left[] = $v;
            }
        }
        $data['middle'] = $middle;
        $data['right'] = $right;
        $data['left'] = $left;
        return ['code'=>200,'msg'=>'排行榜','sec'=>1,'data'=>$data,'text'=>'最后10秒钟，比赛就结束了，恭喜今天的前三名','start_time'=>date('Y-m-d H:i:s',$this->start_time),'end_time'=>date('Y-m-d H:i:s',$this->end_time)];
    }



    public function yuangong_paiming(Request $request)
    {
        $data['name'] = Worker::where('id',$request->id)->value('name');
        $data['top'] = date('Y-m-d');
        $data['today'] = round(Worker::where('id',$request->id)->value('end_number'));
        $data['countdown'] =$this->countdown();
        $al = Worker::field('id,name,end_number,start_number')->where('end_number','>=',0)->order('end_number','desc')->select();

        foreach ($al as &$v){
            $this->countdownif($v);
        }
        $all = list_order($al->toArray(),'end_number','desc');
        $middle = [];
        $right = [];
        $i=0;
        $a = 0;
        $id =$request->id;

        foreach ($all as $k => &$v) {
            $v['status'] = 0;
            if ($v['id'] == $id) {
                $a = $k;
                $v['status'] = 1;
            }
            $v['no'] = ++$i;
            if ($k < 3) {

                $middle[] = $v;
            } else {

                $right[] = $v;
            }

        }

        $min_k=0;
        $max_k=count($right);
        $now_k =0;

        $d =  array_column($right,'id');

        foreach ($right as $kkk=> $vvv){
            if($id==$vvv['id']){
                $now_k = $kkk;
            }
        }

        $r=[];
        if($a > 2 && $now_k > 0){
            $r[] = $right[$now_k-1];
        }
        if($a > 2){

            $r[] = $right[$now_k];
        }


        if($a > 2 && $now_k < $max_k){
            $r[] = $right[$now_k+1];
        }

//        $data['middle'] = $middle;
////        $right = Worker::field('id,name,end_number,start_number')->where('end_number','>',0)->where('id','not in',$first)->order('end_number','desc')->select();
////
////        foreach ($right as &$v){
////            $v['end_number'] = round($v['end_number']-(time()-$this->start_time)*$v['start_number']/($this->end_time-$this->start_time));
////        }
//        $data['right'] = $right;

        $data['up'] = $middle;
        $data['down'] = $r;
        return ['code'=>200,'sec'=>1,'msg'=>array_column($all,'id'),'data'=>$data,'text'=>'最后10秒钟，比赛就结束了，恭喜今天的前三名','start_time'=>$this->start_time,'end_time'=>$this->end_time];
    }

    public function login(Request $request)
    {
        $mobile = Company::where('admin_name', $request->mobile)->find();
        return ['code' => 200, 'msg' => '登录', 'data' => $mobile];
    }

    public function yuangong_login(Request $request)
    {
        $mobile = Worker::where('mobile', $request->mobile)->find();
        return ['code' => 200, 'msg' => '员工登录', 'data' => $mobile];
    }
//    public function yuangong_paiming(Request $request)
//    {
//        $data['name'] = '刘飞';
//        $data['top'] = date('Y-m-d');
//        $data['today'] = 2000;
//        $data['countdown'] =$this->countdown();
//        $first = Worker::field('id,name,end_number,start_number')->where('end_number','>',0)->order('end_number','desc')->limit(3)->column('id');
//        $middle = Worker::field('id,name,end_number,start_number')->where('end_number','>',0)->where('id','in',$first)->order('end_number','desc')->select();
//        foreach ($middle as &$v){
//            $v['end_number'] = round(-$v['start_number']+$v['end_number']+(time()-$this->start_time)*$v['start_number']/($this->end_time-$this->start_time));
//        }
//
//        $right = Worker::field('id,name,end_number,start_number')->where('end_number','>',0)->where('id','not in',$first)->order('end_number','desc')->select();
//        foreach ($right as &$v){
//            $v['end_number'] = round(-$v['start_number']+$v['end_number']+(time()-$this->start_time)*$v['start_number']/($this->end_time-$this->start_time));
//        }
//
//        $data['up'] = $middle;
//        $data['down'] = $right;
//        return ['code'=>200,'msg'=>'排行榜','data'=>$data,'text'=>'最后10秒钟，比赛就结束了，恭喜今天的前三名','start_time'=>$this->start_time,'end_time'=>$this->end_time];
//    }


    public function onoff(){
        return ['code'=>200,'msg'=>'开关','data'=> \app\console\model\Config::where('varname','web_switch')->value('varvalue')];
    }

    public function index2(Request $request)
    {
        try {
            $banner = (new \app\model\Banner())->select()->visible(['id', 'single_pic']);
            $notice = (new \app\model\Notice())->where(['index_status' => 1, 'status' => 1])->select()->visible(['id', 'title']);
            $article_type = (new ArticleType())->where(['status' => 1])->order(['sort'=>'asc'])->select()->visible(['id', 'as','title','single_pic']);
            $article = (new Article())->where(['status' => 1, 'index_status' => 1])->order($this->order)->paginate(10)->visible(['id','article_type_id','title','single_pic','price','freight_fee','company_name','create_time']);
            $data['banner'] = $banner;
            $data['notice'] = $notice;
            $data['article_type'] = $article_type;
            $data['article'] = $article;
            return ['code' => 200, 'msg' => '首页', 'data' => $data,'refresh'=>'y'];
        } catch (\Exception $e) {
            return ['code' => 200, 'msg' => $e->getMessage(), 'data' => []];
        }

    }

    public function index(Request $request)
    {
        $banner = (new \app\model\Banner())->select();

        return view('',['banner'=>(new \app\model\Banner())->select()]);
        return ['code'=>200];
    }

    public function search_result(){
        return view();
    }



    public function cart(){
        return view();
    }
    public function add_address(){
        return view();
    }
    public function classification(){
        return view();
    }
    public function commission(){
        return view();
    }
    public function commission2(){
        return view();
    }
    public function goods_detail(){
        $data = SelfModel::find(input('id'));
        return view('',['data'=>$data]);
    }
    public function integral(){
        return view();
    }

    public function logistics(){
        return view();
    }
    public function my(){
        return view();
    }
    public function my_address(){
        return view();
    }
    public function my_bank(){
        $data = \app\model\Bank::where('status',1)->column('title');

        return view('',['data'=>json_encode($data)]);
    }
    public function my_user(){
        return view();
    }
    public function order(){
        return view();
    }
    public function order_detail(){
        return view();
    }

    public function order_refund()
    {
        return view();
    }
    public function member_detail()
    {
        return view();
    }

    public function order_submit(Request $request)
    {
        return view('', []);
        if (isset($request->code)) {
            //  var_dump($request->code);
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . config('wechat')['mobile']['appid'] . "&secret=" . config('wechat')['mobile']['secret'] . "&code=" . $request->code . "&grant_type=authorization_code";
            $json = http_request($url);
            $arr = json_decode($json, true);

            $get_userinfo = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $arr['access_token'] . "&openid=" . $arr['openid'] . "&lang=zh_CN";
            $json2 = json_decode(http_request($get_userinfo), true);
            return view('', ['openid' => $json2['openid'], 'url' => '']);
        } else {
            $rand = rand(10000, 99999);
            $to_url = url('order_submit', [], true, true)->build();
//        $to_url = 'https://xinshepinxiaofang.top/mobile/Member/check_wechat.html';
            $redirect_uri = urlencode($to_url);

            $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . config('wechat')['mobile']['appid'] . "&redirect_uri=" . $redirect_uri . "&response_type=code&scope=snsapi_userinfo&state=" . $rand . "&connect_redirect=1#wechat_redirect";
            return view('', ['url' => $url, 'openid' => '']);
        }

    }
    public function pay_success(){
        return view();
    }
    public function performance(){
        return view();
    }
    public function position(){
        return view();
    }
    public function poster(Request $request){
        $data = \app\model\Member::where('id', $request->member_ids)->withoutField(['password','pay_passwrod'])->find();

        $id_image = './qrcode/'.$data['id'].'_image'.'.png';
        if(file_exists($id_image) ===false){

            $url = url('api/index/index',['invite_code' => $data['invite_code']],false,true)->build();
            $result = Builder::create()
                ->writer(new PngWriter())
                ->writerOptions([])
                ->data($url)
                ->encoding(new Encoding('UTF-8'))
                ->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
                ->size(300)
//           ->margin(40)
                ->roundBlockSizeMode(new RoundBlockSizeModeMargin())
//           ->logoPath(root_path().'/logo.png')
//            ->logoResizeToWidth(300)
                ->labelText($data['invite_code'])
                ->labelFont(new NotoSans(25))
//        ->labelAlignment(new LabelAlignmentCenter())
                ->validateResult(false)
                ->build()->saveToFile(root_path().'/public/qrcode/'.$data['id'].'.png');

            $image = \think\Image::open('./bg.png');
            $width =  $image->width();//背景图
            $witch2 = \think\Image::open('./qrcode/'.$data['id'].'.png')->width();//二维码
            $with = ($width-$witch2)/2;

            $image->water('./qrcode/'.$data['id'].'.png',[$with,780])->save($id_image);
        }


        return view('',['data'=>request()->domain().'/qrcode/'.$data['id'].'_image'.'.png?rand='.mt_rand(1000,9999)]);
    }
    public function quickLogin(){
        return view();
    }
    public function quickLogin2(){
        return view();
    }
    public function register(){
        $this->numStr();
        return view();
    }

    public function search(){
        return view();
    }
    public function searchResult(){
        return view();
    }
    public function set(){
        return view();
    }
    public function update_information(){
        return view();
    }
    public function update_loginpsd(){
        return view();
    }
    public function update_paypsd(){
        return view();
    }
    public function update_phone(){
        return view();
    }
    public function upload_documents(){
        return view();
    }
    public function withdrawal_bankcard(){
        return view();
    }
    public function withdrawal_detail(){
        return view();
    }
    public function withdrawal_wechat(){
        return view();
    }










    /**
     * 会员登录
     */
    public function logins(Request $request)
    {

        try {
            $member = SelfModel::where('login_account', $request->mobile)->find();
            if (empty($member)) {
                return ['code' => 400, 'msg' => '用户名不存在'];
            } else {
                $member = $member->where('login_account', $request->mobile)->where('login_password', $request->password)->withoutField(['login_password'])->find();
                if (empty($member)) {
                    return ['code' => 400, 'msg' => '密码错误'];
                }

                $old_token = MemberToken::where('member_id', $member->id)->select();
                foreach ($old_token as $v) {
                    JWTAuth::invalidate($v['token']);
                    MemberToken::destroy(['member_id' => $member->id]);
                }
                if($member['company_id'] > 0){
                    $last_id = $member['company_id'] ;
                }else{
                    $last_id = $member['id'] ;
                }
                $member['token'] = JWTAuth::builder(['member_id' => $member->id]);
                MemberToken::create(['member_id' => $member->id, 'token' => $member['token']]);
                return ['code' => 200, 'msg' => '登录成功', 'data' => ['id'=>$last_id]];
            }
        }  catch (\Exception $e) {
            return ['code' => 200, 'msg' => $e->getMessage(), 'data' => []];
        }
    }


    public function share_view(Request $request){

        return view();
    }



    public function version(Request $request)
    {
        return ['code' => 200, 'msg' => '可以更新', 'data' => hexdec('1010,1000')];
        return hexdec('1010 1000');
        if ($request->version != cache('web_version')) {
           // return ['code' => 400, 'msg' => '版本号不对', 'data' => ['version' => (int)cache('web_version')]];
        }
        $data = ['version' => (int)cache('web_version'), 'is_force_update' => 'yes', 'download_url' => 'url', 'content' => '更新内容'];
        return ['code' => 200, 'msg' => '可以更新', 'data' => $data];
    }




    public function push()
    {
        // 1.当前任务将由哪个类来负责处理。
        //   当轮到该任务时，系统将生成一个该类的实例，并调用其 fire 方法
        try {
            $jobHandlerClassName = 'app\api\controller\index@tast';// 2.当前任务归属的队列名称，如果为新队列，会自动创建
            $jobQueueName = "helloJobQueue";// 3.当前任务所需的业务数据 . 不能为 resource 类型，其他类型最终将转化为json形式的字符串
            //   ( jobData 为对象时，存储其public属性的键值对 )
            $jobData = ['ts' => time(), 'remark'=>'推送'];// 4.将该任务推送到消息队列，等待对应的消费者去执行
            $isPushed = Queue::later(15,$jobHandlerClassName, $jobData, $jobQueueName);// database 驱动时，返回值为 1|false  ;   redis 驱动时，返回值为 随机字符串|false
            if ($isPushed !== false) {
                echo date('Y-m-d H:i:s') . " a new Hello Job is Pushed to the MQ" . "<br>";
            } else {
                echo 'Oops, something went wrong.';
            }
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
    }


    /**
     * fire方法是消息队列默认调用的方法
     * @param Job            $job      当前的任务对象
     * @param array|mixed    $data     发布任务时自定义的数据
     */
    public function tast(Job $job,$data)
    {


        // 有些消息在到达消费者时,可能已经不再需要执行了
        $isJobStillNeedToBeDone = $this->checkDatabaseToSeeIfJobNeedToBeDone($data);
        if(!$isJobStillNeedToBeDone){
            $job->delete();
            return;
        }

        $isJobDone = $this->doHelloJob($data);

        if ($isJobDone) {
            // 如果任务执行成功， 记得删除任务
            $job->delete();
            print("<info>Hello Job has been done and deleted"."</info>\n");
        }else{

            if ($job->attempts() > 3) {
                //通过这个方法可以检查这个任务已经重试了几次了
                print("<warn>Hello Job has been retried more than 3 times!"."</warn>\n");
                $job->delete();

                // 也可以重新发布这个任务
                //print("<info>Hello Job will be availabe again after 2s."."</info>\n");
                //$job->release(2); //$delay为延迟时间，表示该任务延迟2秒后再执行
            }
        }
    }

    /**
     * 有些消息在到达消费者时,可能已经不再需要执行了
     * @param array|mixed    $data     发布任务时自定义的数据
     * @return boolean                 任务执行的结果
     */
    private function checkDatabaseToSeeIfJobNeedToBeDone($data){
        return true;
    }

    private function doHelloJob($data) {
        // 根据消息中的数据进行实际的业务处理...

        print("<info>Hello Job Started. job Data is: ".var_export($data,true)."</info> \n");
        print("<info>Hello Job is Fired at " . date('Y-m-d H:i:s') ."</info> \n");
        print("<info>Hello Job is Done!"."</info> \n");

        return true;
    }



}